import uuid
import datetime


# 查询集转化为列表
def queryset_to_list(query):
    return list(map(lambda info: dict(info), query))


# 查询条件转化为字典
def query_to_dict(query, needPage="0"):
    result = {}
    keys = list(dict(query).keys())
    page = 1
    size = 10
    if "page" in keys:
        keys.remove("page")
        page = query.get("page")
    if "size" in keys:
        keys.remove("size")
        size = query.get("size")
    for k in keys:
        result[k] = query.get(k)
    if needPage == "0":
        return result
    else:
        return (result, page, size)


"""
从目标字典中去除指定字段
"""


def remove_item_form_dict(info, remove_keys):
    result = {}
    remove_info = {}
    keys = list(dict(info).keys())
    for remove_key in remove_keys:
        if remove_key in keys:
            keys.remove(remove_key)
            remove_info[remove_key] = info[remove_key]
    for key in keys:
        result[key] = info[key]
    return (result, remove_info)


# 组装新增参数
def insert_dict_factory(insert_dict):
    now = str(datetime.datetime.now())
    insert_dict["uid"] = uuid.uuid1().hex
    insert_dict["create_time"] = now
    insert_dict["update_time"] = now
    return insert_dict


def insert_dict_factory_no_uid(insert_dict):
    """
    添加创建时间
    """
    now = str(datetime.datetime.now())
    insert_dict["create_time"] = now
    insert_dict["update_time"] = now
    return insert_dict


# 处理datatime型数据
def make_datetime(datetime):
    return datetime.strftime("%Y-%m-%d %H:%M:%S")


"""
处理
"""


def make_result_time(info):
    info["create_time"] = str(info["create_time"])
    info["update_time"] = str(info["update_time"])
    return info


def date_to_month(date):
    year = date.year
    if date.month < 10:
        month = "0{}".format(date.month)
    else:
        month = date.month
    return "{}-{}".format(year, month)


def month_day(date: datetime):
    """
    获取 date 月有多少天
    """
    Year = date.year
    Month = date.month
    # 31天的情况判断
    if (Month == 1 or Month == 3 or Month == 5 or Month == 7 or Month == 8
            or Month == 10 or Month == 12):
        return 31
    # 30天的情况判断
    elif (Month == 4 or Month == 6 or Month == 9 or Month == 11):
        return 30
    # 闰年2月判断
    elif Month == 2 and ((Year % 4 == 0 and Year % 100 != 0) or Year % 400 == 0):
        print('本月29天')
        return 29
    # 28天情况判断
    else:
        return 28


def get_member_add_delateDays(monthNum: int):
    """
    获取会员增加天数
    """
    today = datetime.datetime.today()
    deltaDays = 0
    for i in range(monthNum):
        target_month = (today.month + i) % 12
        if target_month == 0:
            target_month = 12
        targetDate = datetime.datetime(year=today.year, month=target_month, day=today.day)
        print("month:{} days:{}".format(target_month, month_day(targetDate)))
        deltaDays += month_day(targetDate)
    return datetime.timedelta(days=deltaDays)
